package com.xuanwu.ai.flow.service;

import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.dto.FlowAccountReqDTO;
import com.xuanwu.ai.flow.mapper.TenantFlowAccountMapper;
import com.xuanwu.ai.flow.model.TenantFlowAccount;
import com.xuanwu.ai.jdbc.mybatis.LambdaExcludeEmptyQueryWrapper;
import com.xuanwu.ai.web.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class TenantFlowAccountServiceImpl {

    @Autowired
    private TenantFlowAccountMapper tenantFlowAccountMapper;

    /**
     * 创建租户流程账号
     *
     * @param flowAccountReqDTO
     */
    public void createTenantFlowAccount(FlowAccountReqDTO flowAccountReqDTO) {

        int exitCount = tenantFlowAccountMapper.selectCount(new LambdaExcludeEmptyQueryWrapper<TenantFlowAccount>()
                .eq(TenantFlowAccount::getTenantId, flowAccountReqDTO.getTenantId()));

        if (exitCount > 0) {
            throw new BizException(ErrorCodeEnum.TENANT_FLOW_ACCOUNT_REPEAT);
        }

        TenantFlowAccount tenantFlowAccount = new TenantFlowAccount();
        tenantFlowAccount.setTenantId(flowAccountReqDTO.getTenantId());
        tenantFlowAccount.setTenantName(flowAccountReqDTO.getTenantName());
        tenantFlowAccount.setFlowAccount(String.valueOf(flowAccountReqDTO.getTenantId()));
        tenantFlowAccount.setFlowAccessKey(UUID.randomUUID().toString().replace("-", ""));
        tenantFlowAccount.setCreateTime(new Date());
        tenantFlowAccount.setStatus(1);

        tenantFlowAccountMapper.insert(tenantFlowAccount);
    }

}
